package com.howard.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * 资源文件工具
 *
 * @author <a href="mailto:howard.he0329@gmail.com">Howard.He</a>
 *
 */
public final class ResourceUtils {

	private static Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

	private static final String CLASSPATH_URL_PREFIX = "classpath:";
	private static final String URL_PROTOCOL_FILE = "file";

	private ResourceUtils() {
	}

	/**
	 * 放在classpath 下的资源文件 如： classpath:xxx.properties
	 *
	 * @param resourceLocation
	 *            资源文件名
	 * @return File 文件
	 * @throws FileNotFoundException
	 *
	 */
	public static File getFile(String resourceLocation)
			throws FileNotFoundException {
		if (StringUtils.startsWith(resourceLocation, CLASSPATH_URL_PREFIX)) {
			URL url = Thread
					.currentThread()
					.getContextClassLoader()
					.getResource(
							resourceLocation.substring(CLASSPATH_URL_PREFIX
									.length()));
			if (url == null) {
				throw new FileNotFoundException(" resource ["
						+ resourceLocation + "]"
						+ " cannot be resolved to absolute file path "
						+ "because it does not reside in the file system");
			}
			return getFile(url);
		}
		try {
			return getFile(new URL(resourceLocation));
		} catch (MalformedURLException e) {
			logger.info("[" + resourceLocation + "] " + e.getMessage());
			return new File(resourceLocation);
		}
	}

	/**
	 *
	 * @param url
	 * @return File
	 * @throws FileNotFoundException
	 */
	public static File getFile(URL url) throws FileNotFoundException {
		if (url == null) {
			throw new IllegalArgumentException("Resource URL must not be null");
		}
		if (!URL_PROTOCOL_FILE.equals(url.getProtocol())) {
			throw new FileNotFoundException(
					"because it does not reside in the file system: "
							+ url.toString());
		}
		try {
			URI uri = toURI(url);
			return new File(uri.getSchemeSpecificPart());
		} catch (URISyntaxException e) { // uri sytax
			e.printStackTrace();
			return new File(url.getFile());
		}
	}

	/**
	 *
	 * @param URL
	 *            url
	 * @return URL
	 * @throws URISyntaxException
	 */
	public static URI toURI(URL url) throws URISyntaxException {
		return toURI(url.toString());
	}

	/**
	 *
	 * @param location
	 * @return URI
	 * @throws URISyntaxException
	 */
	public static URI toURI(String location) throws URISyntaxException {
		return new URI(StringUtils.replace(location, " ", "%20"));
	}
}
